package com.xc.common.tool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;

public class ImageToBAse64Converter {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    public static void main(String[] args) {
        String filepath = "http://127.0.0.1:89/zdtest/2024-03-08/1877288010878423044.jpg";
        String str = "abcac";
        String b = str.replace("a","B");
        System.out.println("b = " + b);
    }
    public static String imageToBase64(InputStream fis){

        try{
            byte[] imgBytes= new byte[fis.available()];
            fis.read(imgBytes);
            fis.close();
            String base64 = Base64.getEncoder().encodeToString(imgBytes);
            return base64;
        }catch (IOException e){
            e.printStackTrace();
            return null;
        }
    }
    public static String imageToBase64(String filepath){
        if(filepath.indexOf("http")==-1){
            try{
                FileInputStream fin = new FileInputStream(filepath);
                byte[] imgBytes= new byte[fin.available()];
                fin.read(imgBytes);
                fin.close();
                String base64 = Base64.getEncoder().encodeToString(imgBytes);
                return base64;
            }catch (IOException e){
                e.printStackTrace();
                return null;
            }
        }else{
            URL url = null;
            InputStream fis = null;
            try {
                url = new URL(filepath);
                BufferedImage image = ImageIO.read(url);
                URLConnection conn = url.openConnection();
                fis = conn.getInputStream();
            } catch (MalformedURLException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            String base64 = imageToBase64(fis);
            return base64;
        }
    }
}
